<template>
  <div class="scripts-page">
    <div class="page-header">
      <h1>脚本管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        创建脚本
      </el-button>
    </div>

    <!-- 错误信息显示 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert
        :title="errorMessage"
        type="error"
        show-icon
        closable
        @close="errorMessage = ''"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="scripts.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无脚本" />
      <el-button type="primary" @click="showCreateDialog = true">
        创建第一个脚本
      </el-button>
    </div>

    <!-- 脚本表格 -->
    <div v-else>
      <el-table 
        :data="scripts" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="name" label="脚本名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="language" label="语言" width="100">
          <template #default="scope">
            <el-tag :type="getLanguageType(scope.row.language)">
              {{ getLanguageName(scope.row.language) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'info'">
              {{ scope.row.is_active ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="executeScript(scope.row.id)"
              :disabled="!scope.row.is_active"
            >
              执行
            </el-button>
            <el-button size="small" @click="editScript(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteScript(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建/编辑脚本对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingScript ? '编辑脚本' : '创建脚本'"
      width="90%"
      style="max-width: 1200px;"
      class="script-dialog"
      @opened="onDialogOpened"
      @closed="resetForm"
    >
      <el-form
        :model="scriptForm"
        :rules="scriptRules"
        ref="scriptFormRef"
        label-width="80px"
        class="script-form"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="scriptForm.name" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="scriptForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入脚本描述"
          />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-select v-model="scriptForm.language" @change="onLanguageChange">
            <el-option label="Python" value="python" />
            <el-option label="Shell" value="shell" />
            <el-option label="JavaScript" value="javascript" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="scriptForm.is_active" />
        </el-form-item>
        <el-form-item label="内容" prop="content" class="editor-form-item">
          <div class="editor-wrapper">
            <EditorToolbar
              :language="scriptForm.language"
              :theme="editorTheme"
              :font-size="editorFontSize"
              @language-change="onToolbarLanguageChange"
              @theme-change="onThemeChange"
              @font-size-change="onFontSizeChange"
              @insert-template="onInsertTemplate"
            />
            <AceEditor
              v-model="scriptForm.content"
              :language="scriptForm.language"
              :theme="editorTheme"
              :font-size="editorFontSize"
              :height="editorHeight"
              :auto-width="true"
              @init="onEditorInit"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveScript" :loading="saving">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'
import AceEditor from '../components/AceEditor.vue'
import EditorToolbar from '../components/EditorToolbar.vue'
import { ensureArray, cleanScriptData } from '../utils/validation'

export default {
  name: 'Scripts',
  components: {
    AceEditor,
    EditorToolbar
  },
  setup() {
    const router = useRouter()
    const scripts = ref([])
    const showCreateDialog = ref(false)
    const editingScript = ref(null)
    const editorInstance = ref(null)
    const editorTheme = ref('monokai')
    const editorFontSize = ref(14)
    const editorHeight = ref('500px')
    const loading = ref(false)
    const saving = ref(false)
    const errorMessage = ref('')
    
    const scriptForm = ref({
      name: '',
      description: '',
      language: 'python',
      content: '',
      is_active: true
    })
    
    const scriptRules = {
      name: [
        { required: true, message: '请输入脚本名称', trigger: 'blur' },
        { min: 1, max: 100, message: '脚本名称长度在 1 到 100 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入脚本内容', trigger: 'blur' },
        { min: 1, message: '脚本内容不能为空', trigger: 'blur' }
      ]
    }
    
    const scriptFormRef = ref(null)

    // 模板内容
    const templates = {
      python: `#!/usr/bin/env python3
"""
脚本描述
"""

import os
import sys
import time

def main():
    print("脚本开始执行...")
    
    try:
        # 在这里编写你的主要逻辑
        for i in range(5):
            print(f"执行步骤 {i+1}/5")
            time.sleep(1)
        
        print("脚本执行成功!")
        return 0
    except Exception as e:
        print(f"脚本执行失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
`,

      shell: `#!/bin/bash
# 脚本描述

set -e  # 遇到错误立即退出

echo "脚本开始执行..."

# 在这里编写你的主要逻辑
for i in {1..5}; do
    echo "执行步骤 $i/5"
    sleep 1
done

echo "脚本执行成功!"
`,

      javascript: `#!/usr/bin/env node
/**
 * 脚本描述
 */

console.log("脚本开始执行...");

// 在这里编写你的主要逻辑
async function main() {
    try {
        for (let i = 1; i <= 5; i++) {
            console.log(\`执行步骤 \${i}/5\`);
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
        
        console.log("脚本执行成功!");
        process.exit(0);
    } catch (error) {
        console.error("脚本执行失败:", error);
        process.exit(1);
    }
}

main();
`
    }

    // 监听语言变化，自动插入模板
    watch(() => scriptForm.value.language, (newLanguage) => {
      if (!scriptForm.value.content || scriptForm.value.content.trim() === '') {
        scriptForm.value.content = templates[newLanguage] || ''
      }
    })

const fetchScripts = async () => {
  loading.value = true
  errorMessage.value = ''
  try {
    console.log('开始获取脚本列表...')
    const response = await api.get('/scripts/')
    console.log('脚本列表响应:', response.data)
    
    // 确保 scripts 是数组
    scripts.value = Array.isArray(response.data) ? response.data : []
    
    if (scripts.value.length === 0) {
      console.log('脚本列表为空')
    } else {
      console.log(`成功获取 ${scripts.value.length} 个脚本`)
    }
  } catch (error) {
    console.error('获取脚本列表失败:', error)
    const message = error.response?.data?.detail || error.message || '获取脚本列表失败'
    errorMessage.value = message
    
    // 如果是 404 错误，可能是 API 路径问题
    if (error.response?.status === 404) {
      errorMessage.value = 'API 端点未找到，请检查后端服务配置'
    }
    
    ElMessage.error(message)
    
    // 如果是认证错误，跳转到登录页
    if (error.response?.status === 401) {
      router.push('/login')
    }
  } finally {
    loading.value = false
  }
}

    const executeScript = async (scriptId) => {
      try {
        const response = await api.post(`/scripts/${scriptId}/execute`)
        ElMessage.success('脚本开始执行')
        
        // 可以跳转到执行日志页面查看执行进度
        setTimeout(() => {
          router.push(`/execution-logs?log_id=${response.data.execution_id}`)
        }, 1000)
      } catch (error) {
        console.error('执行脚本失败:', error)
        const message = error.response?.data?.detail || error.message || '执行脚本失败'
        ElMessage.error(message)
      }
    }

    const editScript = (script) => {
      editingScript.value = script
      scriptForm.value = { ...script }
      showCreateDialog.value = true
      
      // 确保编辑器已经初始化后再设置内容
      nextTick(() => {
        if (editorInstance.value) {
          editorInstance.value.setValue(scriptForm.value.content)
        }
      })
    }

    const deleteScript = async (scriptId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个脚本吗？此操作不可恢复。', '警告', {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        })
        
        await api.delete(`/scripts/${scriptId}`)
        ElMessage.success('删除成功')
        fetchScripts()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除脚本失败:', error)
          const message = error.response?.data?.detail || error.message || '删除失败'
          ElMessage.error(message)
        }
      }
    }

    const handleSaveScript = async () => {
      if (!scriptFormRef.value) return

      try {
        // 验证表单
        await scriptFormRef.value.validate()
        
        saving.value = true
        const formData = { ...scriptForm.value }
        
        if (editingScript.value) {
          // 更新脚本
          await api.put(`/scripts/${editingScript.value.id}`, formData)
          ElMessage.success('更新成功')
        } else {
          // 创建脚本
          await api.post('/scripts/', formData)
          ElMessage.success('创建成功')
        }
        
        showCreateDialog.value = false
        resetForm()
        fetchScripts()
      } catch (error) {
        console.error('保存脚本失败:', error)
        if (error.name !== 'Cancel') {
          const message = error.response?.data?.detail || error.message || '保存失败'
          ElMessage.error(message)
        }
      } finally {
        saving.value = false
      }
    }

    const resetForm = () => {
      scriptForm.value = {
        name: '',
        description: '',
        language: 'python',
        content: '',
        is_active: true
      }
      editingScript.value = null
      if (scriptFormRef.value) {
        scriptFormRef.value.clearValidate()
      }
    }

    const onEditorInit = (editor) => {
      editorInstance.value = editor
      console.log('Ace Editor 初始化完成')
    }

    const onLanguageChange = (language) => {
      scriptForm.value.language = language
    }

    const onToolbarLanguageChange = (language) => {
      scriptForm.value.language = language
    }

    const onThemeChange = (theme) => {
      editorTheme.value = theme
    }

    const onFontSizeChange = (fontSize) => {
      editorFontSize.value = fontSize
    }

    const onInsertTemplate = (language) => {
      scriptForm.value.content = templates[language] || ''
      if (editorInstance.value) {
        editorInstance.value.setValue(scriptForm.value.content)
      }
    }

    // 对话框打开后的回调
    const onDialogOpened = () => {
      // 对话框完全打开后调整编辑器大小
      nextTick(() => {
        if (editorInstance.value) {
          editorInstance.value.resize()
          console.log('编辑器大小已调整')
        }
      })
    }

    const getLanguageType = (language) => {
      const types = {
        'python': 'success',
        'shell': 'warning',
        'javascript': 'primary'
      }
      return types[language] || 'info'
    }

    const getLanguageName = (language) => {
      const names = {
        'python': 'Python',
        'shell': 'Shell',
        'javascript': 'JavaScript'
      }
      return names[language] || language
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      try {
        return new Date(dateString).toLocaleString('zh-CN')
      } catch (error) {
        console.error('日期格式化错误:', error)
        return dateString
      }
    }

    onMounted(() => {
      console.log('脚本管理页面已加载')
      fetchScripts()
    })

    return {
      scripts,
      showCreateDialog,
      editingScript,
      scriptForm,
      scriptRules,
      scriptFormRef,
      editorTheme,
      editorFontSize,
      editorHeight,
      loading,
      saving,
      errorMessage,
      executeScript,
      editScript,
      deleteScript,
      handleSaveScript,
      onEditorInit,
      onLanguageChange,
      onToolbarLanguageChange,
      onThemeChange,
      onFontSizeChange,
      onInsertTemplate,
      onDialogOpened,
      getLanguageType,
      getLanguageName,
      formatDate
    }
  }
}
</script>

<style scoped>
.scripts-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.error-message {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state .el-button {
  margin-top: 20px;
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%;
}

.script-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
}

/* 确保表单项目宽度一致 */
.script-form :deep(.el-form-item) {
  width: 100%;
}

.script-form :deep(.el-form-item__content) {
  width: 100%;
}

.script-form :deep(.el-input),
.script-form :deep(.el-textarea),
.script-form :deep(.el-select) {
  width: 100%;
}

/* 编辑器表单项目特殊样式 */
.editor-form-item :deep(.el-form-item__content) {
  line-height: normal;
}
</style>
